package com.fy.fyspace.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy.fyspace.service.TranslationService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@Data
public class TranslationServiceImpl implements TranslationService {

  @Value("${baidu.translate.appId}")
  private String appId;

  @Value("${baidu.translate.securityKey}")
  private String securityKey;

  @Resource
  private OkHttpClient okHttpClient;

  private static final String TRANSLATE_API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";

  @Override
  public String translateToZh(String text) {
    if (text == null || text.trim().isEmpty()) {
      return "";
    }

    try {
      String salt = String.valueOf(System.currentTimeMillis());
      String sign = generateSign(text, salt);

      FormBody formBody = new FormBody.Builder()
          .add("q", text)
          .add("from", "en")
          .add("to", "zh")
          .add("appid", appId)
          .add("salt", salt)
          .add("sign", sign)
          .build();

      Request request = new Request.Builder()
          .url(TRANSLATE_API_URL)
          .post(formBody)
          .build();

      try (Response response = okHttpClient.newCall(request).execute()) {
        if (!response.isSuccessful()) {
          throw new RuntimeException("翻译请求失败: " + response);
        }

        String responseBody = response.body().string();
        JSONObject jsonResponse = JSON.parseObject(responseBody);

        JSONArray transResult = jsonResponse.getJSONArray("trans_result");
        if (transResult != null && !transResult.isEmpty()) {
          return transResult.getJSONObject(0).getString("dst");
        }
      }
    } catch (Exception e) {
      log.error("翻译失败: " + text, e);
    }

    return text;
  }

  @Override
  public String[] translateToZhBatch(String[] texts) {
    if (texts == null || texts.length == 0) {
      return new String[0];
    }

    List<String> translatedTexts = new ArrayList<>();
    for (String text : texts) {
      translatedTexts.add(translateToZh(text));
    }

    return translatedTexts.toArray(new String[0]);
  }

  /**
   * 生成签名
   */
  private String generateSign(String text, String salt) {
    String str = appId + text + salt + securityKey;
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
      StringBuilder sign = new StringBuilder();
      for (byte b : bytes) {
        sign.append(String.format("%02x", b & 0xff));
      }
      return sign.toString();
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("生成签名失败", e);
    }
  }
}